import { useRef, useMemo } from 'react';
import {
  ProFormList,
  ProFormText,
  ProFormRadio,
  ProFormDependency,
  ProFormItem,
} from '@ant-design/pro-form';
import CommonUpload from '@/components/CommonUpload';
import { Cascader, message } from 'antd';
import { UPLOAD_FOLDER } from '@/constants/global.const';
import { values } from 'lodash';
import { cascaderDatas, pageTypeInfo, initInfo } from './mock';
import CardInfo from './components/cardInfo';
import type { FormJumpPageOption } from './type';
import styles from './index.less';

interface IFormJumpPageProps {
  curListLength?: number;
  name: string;
  label: string;
  value?: FormJumpPageOption;
  isShowLabel?: boolean; //是否显示Label
  isShowImg?: boolean;
  isShowTitle?: boolean;
  isShowBtn?: boolean; //是否显示增加、删除按钮
  maxLength?: number;
  onChange?: (v: FormJumpPageOption) => void;
}

const FormJumpPage: React.FunctionComponent<IFormJumpPageProps> = (props) => {
  const {
    name,
    label,
    isShowImg = true,
    isShowTitle = true,
    isShowBtn = true,
    isShowLabel = true,
    maxLength = 0,
    curListLength = 0,
  } = props;

  const actionRef = useRef<any>();

  // 新增数据
  const handleNewItem = (e: any) => {
    e.stopPropagation();
    if (maxLength > 0 && curListLength >= maxLength) {
      message.error(`最多增加${maxLength}条数据`);
    } else {
      actionRef.current?.add(initInfo);
      // const index = list.findIndex((item: any) => Object.keys(item).length === 0);
      // actionRef.current?.remove(index);
    }
  };

  return (
    <div className={styles.formJumpPage}>
      <ProFormList
        actionRef={actionRef}
        name={name}
        label={isShowLabel ? label : null}
        copyIconProps={false}
        creatorButtonProps={
          isShowBtn
            ? {
                creatorButtonText: (
                  <span onClick={(e) => handleNewItem(e)}>
                    {maxLength !== 0 ? label + curListLength + '/' + maxLength : label}
                  </span>
                ),
              }
            : false
        }
        deleteIconProps={
          isShowBtn
            ? {
                tooltipText: '删除',
              }
            : false
        }
        itemRender={({ listDom, action }, { index }) => {
          // 限制最大数 是否展示
          if (maxLength > 0 && index >= maxLength) {
            return null;
          }
          return (
            <div className={styles.pageCard}>
              {listDom}
              <div className={styles.del}>{action}</div>
            </div>
          );
        }}
        creatorRecord={initInfo}
        // actionRender={(field, action) => [
        //   isShowBtn && (
        //     <a key={field.key} onClick={() => actionRef.current?.remove(field.key)}>
        //       删除{field.key}
        //     </a>
        //   ),
        // ]}
        // onAfterAdd={handleNewItem}
      >
        {(_f, _index, action) => {
          const newType = action.getCurrentRowData()?.pageType || 'goods';
          const oldType = action.getCurrentRowData()?.value?.type || 'goods';
          if (newType !== oldType) {
            action.setCurrentRowData({
              value: {
                id: '',
                title: '',
                page: '',
                type: newType,
              },
            });
          }

          // 限制最大数 是否展示
          if (maxLength > 0 && _index >= maxLength) {
            return null;
          }

          return (
            <>
              {isShowTitle && (
                <ProFormText
                  label="页面标题"
                  name="title"
                  placeholder="请输入页面标题"
                  required
                  rules={[{ required: true, message: '请输入页面标题!' }]}
                />
              )}
              {isShowImg && (
                <ProFormItem
                  label={'图片'}
                  name="imageUrl"
                  required
                  rules={[{ required: true, message: '请上传图片!' }]}
                >
                  <CommonUpload
                    folder={UPLOAD_FOLDER.LOTTERYDRAW}
                    maxSize={10240}
                    accept={['.jpg', '.png', '.gif']}
                    extraInfo={false}
                    needCrop={false}
                  />
                </ProFormItem>
              )}
              <ProFormRadio.Group
                label="跳转页面"
                name="pageType"
                options={values(pageTypeInfo)}
                required
              />
              <ProFormItem>
                <ProFormDependency name={['pageType']}>
                  {({ pageType }) => {
                    if (pageType === 'goods' || pageType === 'activity') {
                      return (
                        <>
                          <ProFormItem
                            name={['value']}
                            noStyle
                            rules={[
                              {
                                validator: (_, _value) => {
                                  if (!_value.id) {
                                    if (newType === 'goods') {
                                      return Promise.reject(new Error('请选择商品!'));
                                    }
                                    if (newType === 'activity') {
                                      return Promise.reject(new Error('请选择活动!'));
                                    }
                                  }
                                  return Promise.resolve();
                                },
                              },
                            ]}
                          >
                            <CardInfo pageType={pageType} />
                          </ProFormItem>
                        </>
                      );
                    } else if (pageType === 'specifyPage') {
                      return (
                        <>
                          <ProFormItem
                            name={['value', 'page']}
                            noStyle
                            required
                            rules={[{ required: true, message: '请指定页面!' }]}
                          >
                            <Cascader
                              options={cascaderDatas}
                              placeholder="指定页面"
                              showSearch={true}
                              onSearch={(value) => console.log(value)}
                            />
                          </ProFormItem>
                        </>
                      );
                    } else {
                      return null;
                    }
                  }}
                </ProFormDependency>
              </ProFormItem>
            </>
          );
        }}
      </ProFormList>
    </div>
  );
};

export default FormJumpPage;
